package study.ttl.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import study.ttl.common.Constants;
import study.ttl.common.enums.LogModuleEnum;
import study.ttl.common.enums.ResultCodeEnum;
import study.ttl.common.enums.RoleEnum;
import study.ttl.common.system.AsyncTaskFactory;
import study.ttl.entity.User;
import study.ttl.exception.CustomException;
import study.ttl.mapper.UserMapper;
import study.ttl.service.UserService;
import study.ttl.utils.RedisUtils;
import study.ttl.utils.SaUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @Override
    public User login(User user) {
        // 校验验证码
        String uuid = user.getUuid();
        String captchaKey = Constants.REDIS_KEY_CAPTCHA + uuid;
        String captchaCode = RedisUtils.getCacheObject(captchaKey);
        if (captchaCode == null) {
            throw new CustomException("验证码已过期");
        }
        if (!user.getCode().equals(captchaCode)) {
            throw new CustomException("验证码错误");
        }
        // 验证完成后删除验证码
        RedisUtils.deleteObject(captchaKey);

        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser == null) {
            throw new CustomException("账号或密码错误");
        }

        // 密码加盐
        String md5Password = securePassword(user.getPassword());
        if (!dbUser.getPassword().equals(md5Password)) {
            throw new CustomException("账号或密码错误");
        }

        // 返回token
        StpUtil.login(dbUser.getId());
        String token = StpUtil.getTokenValue();
        dbUser.setToken(token);

        // 异步记录日志
        AsyncTaskFactory.recordLog(LogModuleEnum.USER.value, "登录", dbUser.getId());
        return dbUser;
    }

    /**
     * 添加用户
     *
     * @param user
     */
    @Override
    public void add(User user) {
        if (user.getUsername() == null) {
            throw new CustomException("用户名不能为空");
        }

        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser != null) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }

        if (user.getPassword() == null) {
            user.setPassword(Constants.DEFAULT_PASSWORD);
            user.setPassword(securePassword(user.getPassword()));
        }

        if (user.getName() == null) {
            user.setName(user.getUsername());
        }


        userMapper.insert(user);
    }

    /**
     * 根据id删除用户
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }


    /**
     * 修改用户信息
     *
     * @param user
     */
    @Override
    public void update(User user) {
        userMapper.updateById(user);
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User selectById(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @Override
    public List<User> selectAll(User user) {
        List<User> userList = userMapper.selectAll(user);
        return userList;
    }

    /**
     * 分页查询用户
     *
     * @param pageNum
     * @param pageSize
     * @param user
     * @return
     */
    @Override
    public PageInfo<User> selectPage(Integer pageNum, Integer pageSize, User user) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.selectAll(user);
        return PageInfo.of(userList);
    }

    /**
     * 批量删除用户
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Integer> ids) {
        userMapper.deleteBatch(ids);
    }

    /**
     * 修改密码
     *
     * @param user
     */
    @Override
    public void updatePassword(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser == null) {
            throw new CustomException("账户不存在");
        }


        // 校验身份，如果是管理员，则直接修改密码
        User loginUSer = SaUtils.getLoginUSer();
        if (RoleEnum.USER.name().equals(loginUSer.getRole())) {
            if (!dbUser.getPassword().equals(securePassword(user.getPassword()))) {
                throw new CustomException("原密码错误");
            }
        }


        // 加密新密码
        dbUser.setNewPassword(securePassword(user.getNewPassword()));

        // 异步记录日志
        AsyncTaskFactory.recordLog(LogModuleEnum.USER.value, "修改密码", loginUSer.getId());

        userMapper.updatePassword(dbUser);

    }

    /**
     * 注册用户
     *
     * @param user
     */
    @Override
    public void register(User user) {
        user.setRole(RoleEnum.USER.name());
        // 加密密码
        user.setPassword(securePassword(user.getPassword()));
        this.add(user);
        // 异步记录日志
        AsyncTaskFactory.recordLog(LogModuleEnum.USER.value, "注册", user.getId());

    }

    // 加密密码
    private String securePassword(String password) {
        return SecureUtil.md5(password + Constants.PASSWORD_SALT);
    }

}
